package com.itheima.reflect5;

import java.io.*;
import java.lang.reflect.Field;

public class MyReflectDemo {
    public static void main(String[] args) throws IOException, IllegalAccessException {
        //创建对象
        Student s = new Student("zhangsan", 20);
        Teacher t = new Teacher("lisi", 30, "男");

        //搞个方法实现将所有对象的字段名和值写到文件中
        writeObjectToFile(t);
    }

    private static void writeObjectToFile(Object o) throws IOException, IllegalAccessException {
        //获取到当前对象的字节码文件对象
        Class<?> clazz = o.getClass();
        BufferedWriter bw=new BufferedWriter(new FileWriter("myreflect\\a.txt"));
        //获取到所有的字段
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f : declaredFields) {
            //不知道是不是私有字段，需要暴力破解
            f.setAccessible(true);
            //获取字段名
            String name = f.getName();
            //获取字段值
            Object value = f.get(o);
            bw.write(name+"="+value);
            bw.newLine();
        }
        bw.close();
    }
}
